package com.daxt.websocket;

import java.util.HashMap;
import java.util.Map;

import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import com.alibaba.fastjson.JSON;
import com.daxt.model.service.socket.Message;
import com.daxt.model.service.socket.UserMsg;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

@Component
public class CloudWebSocketHandle extends TextWebSocketHandler{
	//code   0下线 1在线
	//@Autowired
	//private MessageService messageService;
	private static final ObjectMapper MAPPER=new ObjectMapper();
	private static final Map<String,WebSocketSession>  SESSION=new HashMap<>();
	@Override
	protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
		//{"toId":"11","msg":"kkk","username":"admin"}  消息模式
		System.out.println("获取消息。。。"+message.getPayload());
		String uid = session.getAttributes().get("uid").toString();
		System.out.println(JSON.toJSONString(message.getPayload()));
		JsonNode jsonNode = MAPPER.readTree(message.getPayload());
		String toId = jsonNode.get("toId").asText();
		String msg = jsonNode.get("msg").asText();
		String username = jsonNode.get("username").asText();
		
		WebSocketSession webSocketSession = SESSION.get(toId);
		System.out.println(JSON.toJSONString( SESSION.keySet()));
		//判断用户是否在线
		if(webSocketSession!=null&&webSocketSession.isOpen()) {
			Message successEntity =Message.builder()
					.code("1")
					.from(new UserMsg(uid, username))
					.to(new UserMsg(toId, "游客"))
					.msg(msg).build();
			webSocketSession.sendMessage(new TextMessage(MAPPER.writeValueAsString(successEntity)));
			//更新消息已读
			//messageService.updateMessageState(messageEntity.getId(), 2);
		}else {
			WebSocketSession resutnSession = SESSION.get(uid);
			Message errorEntity =Message.builder()
					.code("0")
					.from(new UserMsg(uid, username))
					.to(new UserMsg(uid, username))
					.msg("0".equals(toId)?"客服当前不在线":"用户已下线").build();
			resutnSession.sendMessage(new TextMessage(MAPPER.writeValueAsString(errorEntity)));
		}
	}
	
	@Override
	public void afterConnectionEstablished(WebSocketSession session) throws Exception {
		String uid = session.getAttributes().get("uid").toString();
		System.out.println(uid);
		SESSION.put(uid, session);
		System.out.println("建立连接");
		System.out.println("当前在线人数"+SESSION.size());
	}
	
	@Override
	public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
		String uid = session.getAttributes().get("uid").toString();
		SESSION.remove(uid);
		System.out.println("断开连接");
		System.out.println("当前在线人数"+SESSION.size());
	}
}
